const express = require("express")
const mysql = require("mysql")

let server = express();
server.listen(8088);

const db = mysql.createConnection({
    host:'localhost',
    user: "root",
    password: "",
    database: "20210617"
})


// 1. 检查数据
server.get("/reg", (req, res, next)=> {
    let {user, pass} = req.query

    if(!user){
        res.send({code: 1, msg: "用户名不能为空。"})
    } else if(!pass){
        res.send({code: 1, msg: "密码不能为空。"})
    } else if(!/^\w{6,32}/.test(user)){
        res.send({code: 1, msg: "用户名格式错误！"})
    } else if(!/^.{6,}/.test(pass)){
        res.send({code: 1, msg: "密码格式错误！"})
    } else{
        next()
    }
})

// 2. 有没有这个用户
server.get("/reg", (req, res, next) => {
    let {user, pass} = req.query
    db.query(`select * from user_table where username='${user}'`,(err, data) => {
        if(err) res.send({code: 1, msg: "数据库出错！"})
        else if(data.length > 0){
            res.send({code: 1, msg: "此用户已存在！"})
        } else{
            next()
        }
        
    })
})
// 3. 写入数据
server.get("/reg", (req, res, next) => {
    let {user, pass} = req.query
    db.query(`insert into user_table (username, password) values ('${user}', '${pass}')`, err =>{
        if(err){
            res.send({code: 1, msg: "数据库出错！"})
        } else {
           res.send({code: 0, msg: "注册成功！"})
        }
    })
})

console.log("connection successful.")